﻿using Common;
using Common.ValidHelper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace enterprise.Website.Core
{
    public class WebValidMiddleWare
    {
        private readonly RequestDelegate next;
        public WebValidMiddleWare(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task InvokeAsync(HttpContext context,ExpiredValid expiredValid)
        {
            var Isneed = ConfigHelper.Configuration["WebExpireValid:IsNeedValid"].ToBoolean(false);
            if (Isneed)
            {
                var IsIpLogin = context.Request.Host.Host.IsIpAddress();
                if (IsIpLogin)
                {
                    await next(context);
                    return;
                }
                var validData = expiredValid.GetValidData();
                if (validData.serverEndTime < DateTime.Now)
                {
                    context.Response.Redirect(ConfigHelper.Configuration["WebExpireValid:RedirectPage"]);
                    return;
                }
            }
            await next(context);
        }
    }

    /// <summary>
    /// 扩展方法，将中间件暴露出去
    /// </summary>
    public static class ValidMiddleWare
    {
        /// <summary>
        /// 过期检查
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseValid(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<WebValidMiddleWare>();
        }
    }

}
